<template>
    <div>
        <common-head title="联系人列表"/>
        <van-address-list
        v-model="chosenAddressId"
        :list="contacts"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select='choseContact'
        />
    </div>
</template>

<script>
import CommonHead from '@components/CommonHead'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      chosenAddressId: -1
    }
  },
  created () {
    this.initchoseId()
  },
  methods: {
    choseContact (contact) {
      // 点击切换联系人的时候，会将修改数据交给vuex处理
      this.$store.commit('order/set_order_contact', contact)
      this.$router.replace('/order')
    },
    initchoseId () {
      if (this.contacts.length > 0) {
        // 先获取默认联系人
        const defaultContact = this.contacts.find(el => el.isDefault)
        // 有默认联系人
        if (defaultContact) {
          this.chosenAddressId = defaultContact.id
        } else {
          // 没有默认联系人，就将第一个设置为默认联系人
          this.chosenAddressId = this.contacts[0].id
        }
      } else {
        // 联系人为空
        return false
      }
    },
    onAdd () {
      this.$router.push('/contactAdd')
    },
    onEdit (contact, index) {
      this.$router.push({
        path: '/contactEdit',
        query: {
          index
        }
      })
    }
  },
  components: {
    CommonHead
  },
  computed: {
    ...mapState({
      contacts: state => state.contact.contacts
    })
  }
}
</script>

<style lang="scss" scoped>
.van-address-list{
    padding-top: 50px;
}
</style>
